package com.hf.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hf.entity.Roles;
import com.hf.entity.UserRoles;
import com.hf.service.IUserRolesService;
import com.hf.util.Result;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author eight
 * @since 2021-06-06
 */
@RestController
@RequestMapping("/user-roles")
public class UserRolesController {
	@Autowired
	IUserRolesService iUserRolesService;

	/**
	 * 根据用户id查询用户角色 localhost:8080/user-roles/getRolesByUserId?userId=2
	 * 
	 * @param userId
	 * @return
	 */
	@GetMapping("/getRolesByUserId")
	public Object getRolesByUserId(Integer userId) {
		List<Roles> list = iUserRolesService.getRolesByUserId(userId);
		int num = (iUserRolesService.getRolesByUserId(userId)).size();
		return new Result(0, "查询成功", list, num);

	}

	/**
	 * 根据用户id批量添加（设置）用户角色 localhost:8080/user-roles/insertBatch?userId=3&rids=6,7
	 * 
	 * @param userId 用户id
	 * @param rids   角色字符串，以逗号分隔开
	 * @return
	 */
	@PostMapping("/insertBatch")
	public Object insertBatch(@RequestParam Integer userId, @RequestParam String rids) {
		List<UserRoles> list = new ArrayList<UserRoles>();

		String[] split = rids.split(",");
		for (String m : split) {
			list.add(new UserRoles(userId, Integer.valueOf(m)));
		}

		boolean res = iUserRolesService.saveBatch(list);
		if (res) {
			return new Result(0, "设置成功");
		}
		return new Result(1, "设置失败");

	}

	/**
	 * 批量移除用户角色 localhost:8080/user-roles/deleteBatch?userId=1&rids=5,6
	 * 
	 * @param userId 用户id
	 * @param rids   角色字符串，以逗号分隔开
	 * @return
	 */
	@PostMapping("/deleteBatch")
	public Object deleteBatch(@RequestParam Integer userId, @RequestParam String rids) {
		boolean res = iUserRolesService.deleteByUserIdAndRoleId(userId, rids);

		if (res) {
			return new Result(0, "移除成功");
		}
		return new Result(1, "移除失败");
	}

}
